package jee.boot.module.log.local;

import jee.boot.common.standard.AccountHandler;
import jee.boot.common.utils.SpringContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LogUtils {

    public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";

    /**
     * 保存日志
     */
    public static void saveLog(HttpServletRequest request) {
        saveLog(request, null, null);
    }

    /**
     * 保存日志
     */
    public static void saveLog(HttpServletRequest request, Object user, Exception ex) {
        if (user == null) {
            AccountHandler accountHandler = SpringContextHolder.getApplicationContext().getBean(AccountHandler.class);
            user = accountHandler.getPrincipal();
        }
        String realIp = request.getHeader("x-real-ip");
        Map<String, Object> log = new HashMap<>();
        log.put("type", ex == null ? "1" : "2");
        log.put("exception", ex == null ? null : ex.getMessage());
        log.put("remoteAddr", request.getHeader("x-real-ip"));
        log.put("userAgent", request.getHeader("user-agent"));
        log.put("requestUri", request.getRequestURI());
        log.put("method", request.getMethod());
        log.put("createBy", user);
        log.put("updateBy", user);
        log.put("updateDate", new Date());
        log.put("createDate", new Date());
        // 异步保存日志
        try {
            InterceptorLogEntity entity = new InterceptorLogEntity(log, ex);
            LogThread.interceptorLogQueue.put(entity);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}
